/**
 * 杠杆率趋势
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { XYAxisChartsC, NoDataC, SecondHeaderC } from '../../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin } from 'antd';
import moment from 'moment';
import { namespace } from '@/src/newModels/leverageAnalysis/PortfolioManageLeverageAnalysisM';
import { conversionChartsData, reservedBits } from '@/src/utils/commonFunc';
import { cloneDeep } from 'lodash';
import { times } from 'number-precision';

@Form.create()
class leverageRatio extends PureComponent {
  state = {
    isMarkPoint: true, // 是否展示杠杆率趋势图最大值
    cordonValue: null, // 警戒线
    series: [], // 纵坐标
    xAxis: [], // 横坐标
  };

  componentDidMount() {
    const { searchData } = this.props;
    if (this.props.searchData && this.props.searchData.portfolioCode) {
      this.getData(
        JSON.parse(
          JSON.stringify(searchData)
            .replace(/beginDate/g, 'startDate')
            .replace(/timeRange/g, 'rangeType'),
        ),
      );
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.searchData) !== JSON.stringify(this.props.searchData)) {
      this.getData(
        JSON.parse(
          JSON.stringify(nextProps.searchData)
            .replace(/beginDate/g, 'startDate')
            .replace(/timeRange/g, 'rangeType'),
        ),
      );
    }
  }

  // 获取杠杆率趋势数据
  getData = (searchProps) => {
    const obj = {
      startDate: searchProps.startDate,
      endDate: searchProps.endDate,
      productCode: searchProps.portfolioCode,
    };
    this.props.dispatch({
      type: `${namespace}/queryLeverageTrendChart`,
      payload: { ...obj },
      callback: (res) => {
        const [xAxisData, seriesData] = conversionChartsData(res);
        const copySeriesData = cloneDeep(seriesData);
        copySeriesData.map((v) => {
          v.data = v.data.map((item) => (item ? times(item, 100) : item));
        });
        const elementsAreEqual = copySeriesData[0].data.every((el) => el === copySeriesData[0]?.data[0]);
        this.setState({
          series: [...copySeriesData],
          cordonValue: res[0]?.cordonValue ? times(res[0]?.cordonValue, 100) : 0,
          xAxis: xAxisData,
          isMarkPoint: !elementsAreEqual,
        });
      },
    });
  };

  render() {
    const { isMarkPoint, series, xAxis, cordonValue } = this.state;
    const minY =
      series.length > 0 && (Math.min(...series[0].data?.filter((v) => v !== null)) > 90 ? 90 : Math.floor(Math.min(...series[0].data.filter((v) => v !== null)) / 10) * 10);

    return (
      <div style={{ width: '100%', height: '100%' }}>
        {/* 净值趋势 */}
        <SecondHeaderC title='杠杆率趋势' />
        <Spin spinning={this.props.loading.effects[`${namespace}/queryLeverageTrendChart`] == true}>
          {series?.length > 0 && xAxis?.length > 0 ? (
            <XYAxisChartsC
              yAxisRange={[[minY]]}
              isMarkPoint={isMarkPoint}
              series={series}
              xAxis={xAxis}
              yAxisUnit={['杠杆率（%）']}
              height={400}
              type='line'
              dataZoom={true}
              cordonConfig={{
                cordonValue,
              }}
            />
          ) : (
            <NoDataC />
          )}
        </Spin>
      </div>
    );
  }
}
export default connect(({ netValueInProM, loading }) => ({
  netValueInProM,
  loading,
}))(leverageRatio);
